﻿using System.Web;
using System.Web.Security;

using MSAcademic.v2.Infrastructure.User;
using MSAcademic.v2.Infrastructure.Utility;

namespace MSAcademic.v2.Infrastructure.Login.Impl
{
    public partial class HttpCookieLoginService : ILoginService
    {
        public void SignIn(string username, bool isLongSession)
        {
            var cookieValue = string.Format("{0}#{1}", _nonceGenerator.GetNewOfRandomLength(), username);
            FormsAuthentication.SetAuthCookie(cookieValue, isLongSession);
        }

        public void SignOut()
        {
            FormsAuthentication.SignOut();
        }

        public IUser TryGetSignedInUser()
        {
            var identity = _httpContextCurrent.User.Identity;
            if (!identity.IsAuthenticated) { return null; }

            var saltedUserUid = identity.Name;
            var username = saltedUserUid.Substring(saltedUserUid.LastIndexOf('#') + 1);
            return _userQueries.TryGetWhereUsername(username);
        }
    }

    public partial class HttpCookieLoginService
    {
        private readonly RandomNonceGenerator _nonceGenerator;
        private readonly HttpContextBase _httpContextCurrent;
        private readonly IUserQueries _userQueries;

        public HttpCookieLoginService(
            RandomNonceGenerator nonceGenerator,
            HttpContextBase httpContextCurrent,

            IUserQueries userQueries)
        {
            _nonceGenerator = nonceGenerator;
            _httpContextCurrent = httpContextCurrent;
            _userQueries = userQueries;
        }
    }
}
